import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'
import router from '@/router'

/**
 * 创建axios实例用于HTTP请求
 * @type {import('axios').AxiosInstance}
 */
export const request = axios.create({
  baseURL: '/api',
  timeout: 15000,
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
   
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 封装一个处理token失效并登出的函数，避免代码重复
const handleTokenExpired = (msg = '登录已过期，请重新登录') => {
  ElMessage.error(msg)
  const userStore = useUserStore()
  userStore.clearUserInfo()
  // 使用 nextTick 或 setTimeout 确保路由跳转前状态已更新
  setTimeout(() => {
    router
      .push({
        path: '/login',
        query: {
          // 记录当前路径，登录后可能需要跳回
          redirect: router.currentRoute.value.fullPath,
        },
      })
      .catch((e) => {
        // 防止重复跳转同一路由报错
        console.warn('Router push failed:', e.message)
        if (e.name !== 'NavigationDuplicated') {
          throw e // Re-throw other errors
        }
      })
  }, 500) // 稍微延迟，让消息显示更友好
  // 仍然需要返回一个reject，中断后续的promise链
  return Promise.reject(new Error(msg))
}

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    const {code, msg} = response.data
    // token过期
    if (code == 401) {
      console.log(response.data)
      return handleTokenExpired()
    } else if(code == 500) {
      // console.log(response.data)
      // ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    }
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)
